package cn.middle.edge.config;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.middle.common.result.UserInfo;

import cn.dev33.satoken.stp.StpInterface;
import cn.dev33.satoken.stp.StpUtil;
import cn.middle.basic.entity.SysMenu;
import cn.middle.basic.entity.SysRole;
import cn.middle.basic.service.SysUserService;

@Component
public class SaTokenPermissionSource implements StpInterface {
	
	
	private static final String PERMISSION =  "permisson";
	private static final String ROLE = "role";
	
	@Autowired
	private SysUserService userService;

	@Override
	public List<String> getPermissionList(Object loginId, String loginType) {
		@SuppressWarnings("unchecked")
		List<String> permissions = (List<String>)StpUtil.getSession().get(PERMISSION);
		if(permissions != null && !permissions.isEmpty()) {
			return permissions;
		}
		
		UserInfo<SysMenu,SysRole> userInfo = userService.getUserInfo(Long.parseLong((String)loginId));
		permissions = userInfo.getPermissions();
		if(permissions != null && !permissions.isEmpty()) {
			StpUtil.getSession().set(PERMISSION, permissions);
		}
		return  permissions != null ? permissions : new ArrayList<>();
	}

	@Override
	public List<String> getRoleList(Object loginId, String loginType) {
		@SuppressWarnings("unchecked")
		List<String> roles = (List<String>)StpUtil.getSession().get(ROLE);
		if(roles != null && !roles.isEmpty()) {
			return roles;
		}
		
		UserInfo<SysMenu,SysRole> userInfo = userService.getUserInfo(Long.parseLong((String)loginId));
		List<SysRole> sysRoles = userInfo.getRoles();
		if(sysRoles != null && !sysRoles.isEmpty()) {
			roles = new ArrayList<>();
			for(SysRole role : sysRoles) {
				roles.add(role.getCode());
			}
			StpUtil.getSession().set(ROLE, roles);
		}
		
		return roles != null ? roles : new ArrayList<>();
	}

	public Long loginId() {
		Object objectId = StpUtil.getLoginId();
		if(objectId instanceof String) {
			return Long.parseLong((String)objectId);
		}else if(objectId instanceof Long) {
			return (Long) objectId;
		}
		return Long.parseLong(objectId.toString());
	}
}
